package cn.bocweb.spinning.view.fragment;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bocweb.spinning.R;
import cn.bocweb.spinning.model.Bean.ErrorBean;
import cn.bocweb.spinning.model.Bean.FirstRewardBean;
import cn.bocweb.spinning.model.Bean.GetIhomeBean;
import cn.bocweb.spinning.model.Bean.IndexSliderBean;
import cn.bocweb.spinning.model.Bean.MatchInviteBean;
import cn.bocweb.spinning.model.Bean.QaListBean;
import cn.bocweb.spinning.model.Bean.SecondRuleBean;
import cn.bocweb.spinning.model.Bean.TestRuleBean;
import cn.bocweb.spinning.model.Bean.UserBean;
import cn.bocweb.spinning.presenter.Imp.UserPresenterImp;
import cn.bocweb.spinning.presenter.UserPresenter;
import cn.bocweb.spinning.util.Constant;
import cn.bocweb.spinning.util.DeviceUtil;
import cn.bocweb.spinning.util.WXUtil;
import cn.bocweb.spinning.view.MainAdapterInterface;
import cn.bocweb.spinning.view.activity.ExerciseActivity;
import cn.bocweb.spinning.view.activity.FirstRewardActivity;
import cn.bocweb.spinning.view.activity.LoginAcivity;
import cn.bocweb.spinning.view.activity.MainActivity;
import cn.bocweb.spinning.view.activity.QuestionDetailActivity;
import cn.bocweb.spinning.view.activity.SecondRuleActivity;
import cn.bocweb.spinning.view.activity.SequenceTestActivity;
import cn.bocweb.spinning.view.activity.SystemMsgActivity;
import cn.bocweb.spinning.view.activity.TestRuleActivity;
import cn.bocweb.spinning.view.adapter.MainRecycleAdapter;
import de.greenrobot.event.EventBus;

/**
 * Created by chenchangxing on 15/12/24.
 */
public class MainFragment extends Fragment {

    List<String> mainList;
    LinearLayout.LayoutParams layout;
    Dialog dialog;
    String userid;
    List<IndexSliderBean.DataBean> mDataBeanList;
    UserPresenter presenter;
    List<String> bannerUri;
    List<String> bannerTitle;
    MainRecycleAdapter mMainRecycleAdapter;
    int friend_1_timeline_2, flag = 0;
    UserBean.DataEntity dataEntity;

    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.main_view)
    RecyclerView mMainView;
    @Bind(R.id.main_btn_system)
    ImageView mMainBtnSystem;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);


        if (Constant.BASE_URL.contains("http://fzdxtpc.zgsxw.com:90/index.php/") && flag == 0) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
            builder.setMessage("您现在使用的是测试服务器，仅供测试使用");
            builder.setTitle("提示");
            builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    flag = 1;
                }
            });
            builder.create().show();
        }
        dataEntity = new UserBean.DataEntity();
        presenter = new UserPresenterImp();
        mDataBeanList = new ArrayList<>();
        bannerUri = new ArrayList<>();
        bannerTitle = new ArrayList<>();
        mMainRecycleAdapter = new MainRecycleAdapter(
                bannerUri,
                mDataBeanList,
                getChildFragmentManager());
        initList();
        initToolbar();
        presenter.indexSlider();
        presenter.getIhomeMain();
        presenter.qaListMain();


        mMainBtnSystem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(userid)) {
                    Intent intent = new Intent(getContext(), LoginAcivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getContext(), SystemMsgActivity.class);
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 12) {
            presenter.qaListMain();
        }
    }

    public void onEventMainThread(QaListBean bean) {
        if (bean.getReturn_code() == 0) {

            mMainRecycleAdapter.setList(bean.getData());
            mMainRecycleAdapter.notifyDataSetChanged();
        } else {
            DeviceUtil.Log(bean.getMsg());
        }
    }

    public void onEventMainThread(IndexSliderBean bean) {
        if (bean.getReturn_code() == 0) {
            mDataBeanList.addAll(bean.getData());
            for (IndexSliderBean.DataBean dataEntity : bean.getData()) {
                bannerUri.add(dataEntity.getPhoto());
            }
            mMainRecycleAdapter.notifyDataSetChanged();
            mMainRecycleAdapter.startTurn();
        }
    }

    public void onEventMainThread(GetIhomeBean bean) {
        if (bean.getReturn_code() == 0) {
            mMainRecycleAdapter.setGetIHome(bean.getData());
            mMainRecycleAdapter.notifyDataSetChanged();
        }
    }

//    public void onEventMainThread(TestRuleBean bean) {
//        if (bean.getReturn_code() == 0) {
//            Intent intent = new Intent(getActivity(), TestRuleActivity.class);
//            intent.putExtra(Constant.TO_TEST_RULE, bean.getUrl());
//            startActivity(intent);
//        }
//    }

//    public void onEventMainThread(FirstRewardBean bean) {
//        Intent intent = new Intent(getActivity(), FirstRewardActivity.class);
//        intent.putExtra(Constant.TO_FIRST_REWARD, bean.getUrl());
//        startActivity(intent);
//    }

//    public void onEventMainThread(SecondRuleBean bean) {
//        if (bean.getReturn_code() == 0) {
//            Intent intent = new Intent(getActivity(), SecondRuleActivity.class);
//            intent.putExtra(Constant.TO_SECOND_RULE, bean.getUrl());
//            startActivity(intent);
//        }
//    }

    public void onEventMainThread(MatchInviteBean bean) {
        if (bean.getReturn_code() == 0) {
            if (friend_1_timeline_2 == 1) {
                WXUtil.WXShareToFriend(bean.getUrl(), getActivity());
            } else {
                WXUtil.WXShareToTimeline(bean.getUrl(), getActivity());
            }
        }
    }

    public void onEventMainThread(ErrorBean bean) {
        DeviceUtil.MyToast(getContext(), bean.getErrorMsg());
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        UserBean.DataEntity dataEntity = new UserBean.DataEntity();
        dataEntity.readInfoFromLocal(getActivity());
        userid = dataEntity.getUserid();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    private void initList() {
        mainList = new ArrayList<>();

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);

        mMainView.setLayoutManager(manager);
        mMainView.setAdapter(mMainRecycleAdapter);

        mMainRecycleAdapter.setMainAdapterInterface(new MainAdapterInterface() {
//            @Override
//            public void testRule() {
//                dataEntity.readInfoFromLocal(getContext());
//                    presenter.testRule();
//            }
//
//            @Override
//            public void getFirstReward() {
//                presenter.getFirstReward(userid);
//            }

            @Override
            public void btnLinkTest() {
                dataEntity.readInfoFromLocal(getContext());
                if (TextUtils.isEmpty(dataEntity.getUserid())) {
                    Intent intent = new Intent(getContext(), LoginAcivity.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getActivity(), ExerciseActivity.class);
                    intent.putExtra(Constant.TRAIN, Constant.SEQUENCE);
                    startActivityForResult(intent, Constant.SEQUENCE_BACK_MAIN);
                }
            }

//            @Override
//            public void getSecondTest() {
//                presenter.secondRule();
//            }


            @Override
            public void shareToWechatFriend() {
                presenter.matchInvite();
                friend_1_timeline_2 = 1;

            }

            @Override
            public void shareToWechatTimeLine() {
                presenter.matchInvite();
                friend_1_timeline_2 = 2;
            }

            @Override
            public void clickToBBS() {
                ((MainActivity) getActivity()).gotoFourm();
            }

            @Override
            public void itemClick(String id) {
                Intent intent = new Intent(getContext(), QuestionDetailActivity.class);
                intent.putExtra(Constant.TO_QA_DETAIL, id);
                startActivityForResult(intent, 12);
            }
        });

    }

    private void initToolbar() {
        mToolbar.setTitle("纺织大学堂");
        mToolbar.setTitleTextColor(getResources().getColor(R.color.white));
        mToolbar.setNavigationIcon(R.mipmap.main_drawer);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DrawerLayout drawerLayout = (DrawerLayout) getActivity().findViewById(R.id.drawer_layout);
                drawerLayout.openDrawer(Gravity.LEFT);
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);

    }
}
